<template src="./template.html"></template>

<style src="./style.css" scoped></style>

<script>
    import navigator from 'utils/navigator';
    import route from 'constants/route';
    import constant from 'constants/constant';
    import modal from 'utils/modal';
    import api from 'api/api';
    import notification from 'utils/notification';
    import cartService from 'services/cartService';

    const globalEvent = weex.requireModule('globalEvent');

    /**数字字符串扩大100倍*/
    function makeInt(numStr) {
        if(typeof numStr === 'undefined' || numStr == '') return 0;
        let str = numStr.toString();
        var numTmp = str.split('.');
        var nums = numTmp[0];
        if(numTmp.length > 1) {
            var val = numTmp[1];
            val = val.length > 1 ? val : val + '0';
            nums += val;
        } else {
            nums += '00';
        }
        var num = parseInt(nums);
        return num;
    }

     /**解析数据*/
    function vendorData(data, vm) {
        //解析用户地址列表
        vm.addressList = data.myaddress || [];
        if(vm.addressList.length > 0) {
            vm.addressList.map((v,i,arr)=>{
                if(v.is_selected == 1 && v.addr_id) { //选中地址
                    vm.addressId = v.addr_id;
                }

                if(v.addr_default == 1) { //默认地址
                    vm.addressDefaultId = v.addr_id;
                }
            });
        }

        //最终订单应付总额
        vm.totalMoney = makeInt(data.totalMoney)/100;

        //绑定用户余额
        if(data.userWallet && data.userWallet.userMoney){
            vm.myMoneyResult = makeInt(data.userWallet.userMoney)/100;
        }

        //店铺列表
        vm.resetShopList(data.newdata);
    }


    export default{
        data(){
            return{
                pageLoaded: false,
                addressList: [], //地址列表
                addressId: null, //当前地址ID
                addressDefaultId: null, //当前默认收货地址ID
                canBuy: true,//默认的为true
                goods: null, //订单参数
                from: null, //默认来自购物车 购物车不需要传参 一键购传参justBuy
                shopList: [],//店铺列表

                orderGoodsArr: [], //结算的全部商品集合(所有店铺)

                isMyMoney: false, //是否使用余额, 默认不使用
                myMoneyResult: 0, //我的余额数量, 默认为0
                costMyMoney: 0, //消耗的余额, 默认为0

                userIssue: {}, //记录用户自提点 key为sid

                orderTotalCoupon: 0,//订单总优惠券
                totalMoney: 0, //未使用余额的初始化订单总价
                actOrderTotalMoney: 0, //最终订单总价（计算是否使用余额）

                timeout: 8000 //请求超时时间
            }
        },
        created(){
            let self = this;
            let config = weex.config;

            if(config.from) {
                self.from = config.from;
                if(self.from && config.goods){ //一键购和购物车勾选商品
                    self.goods = config.goods;
                }
            }

            self.get(data=>{
                vendorData(data,self);
            });

             //监听确认订单编辑收货地址事件
            globalEvent.addEventListener(constant.EVENT_EDIT_ADDRESS_FROM_CONFIRM, function (e) {
                let _data = e.data || {};
                self.addressId = _data.addr_id;
                if(_data.addr_default == 1) {
                    self.removeDefaultAddrSign();
                    self.addressDefaultId = _data.addr_id;
                }

                self.updateConfirm();
                self.addressList.map(function(v,i,arr){
                    if(v.addr_id == _data.addr_id){
                        self.addressList.$set(i,_data);
                        return v;
                    }
                });
            });

             //监听确认订单新建收货地址事件
            globalEvent.addEventListener(constant.EVENT_ADD_ADDRESS_FROM_CONFIRM, function (e) {
                let _data = e.data || {};
                self.addressId = _data.addr_id;
                if(_data.addr_default == 1){
                    self.removeDefaultAddrSign();
                    self.addressDefaultId = _data.addr_id;
                }

                self.addressList.unshift(_data);
                self.$refs.addrList.scrollTo("first");
                self.updateConfirm();
            });

             //监听自提点选择事件
            globalEvent.addEventListener(constant.EVENT_GET_SELFPICK, function (e) {
                let _data = e.data || {};
                let sid = _data.sid;
                let val = _data.value || {};

                self.shopList.map(function(v,i,arr){
                    if(v.sid == sid){
                        v.checkPlotId = val.issue_id || '';
                        v.checkPlotName = val.issue_name || '';
                        self.shopList.$set(i,v);
                        return v;
                    }
                });

                //保存店铺自提点信息
                self.userIssue[sid] = val;
            });
        },
        methods: {
            /**订单确认接口*/
            get(succCallback,failCallback){
                let self = this;
                let params = {
                    address: self.addressId
                };
                if(self.goods) params.goods = self.goods;
                if(self.timeout) params.timeout = self.timeout;
                api.sendHttp('confirmApi',params).then(res => {
                    self.pageLoaded = true;
                    if(typeof succCallback == 'function') succCallback(res.data);
                }, res => {
                    self.pageLoaded = true;
                    modal.toast(res.msg || "获取订单数据失败");
                    if(typeof failCallback == 'function') failCallback(res.data);
                });
            },
            selectAddress(addrId){ //切换收货地址
                let self = this;
                self.addressId = addrId;
                self.updateConfirm();
            },
            delAddress(addrId){ //删除收货地址
                let self = this;
                if(addrId == self.addressId){ //删除当前地址后刷新页面
                    self.addressId = null;
                }

                self.addressList.map(function(v,i,arr){
                    if(v.addr_id == addrId){
                        self.addressList.splice(i,1);
                        return false;
                    }
                });
            },

            /*移除默认收货地址*/
            removeDefaultAddrSign(){
                let self = this;
                if(self.addressDefaultId) {
                    self.addressList.map(function(v,i,arr){
                        if(v.addr_id == self.addressDefaultId){
                            v.addr_default = 0;
                            self.addressList.$set(i,v);
                            return v;
                        }
                    });
                }
            },

            /*更新页面*/
            updateConfirm(){
                this.get(data=>{
                    //最终订单应付总额
                    this.totalMoney = makeInt(data.totalMoney)/100;

                    //店铺列表
                    this.resetShopList(data.newdata);
                });
            },

            /**重置店铺商品列表*/
            resetShopList(list){
                list = list || [];
                let _canBuy = true; //监听是否购买，默认为真
                this.orderTotalCoupon = 0;//重新归0
                for(let i=0; i<list.length; i++){
                    let shop = list[i];

                    this.orderTotalCoupon += makeInt(shop.midcouponmoney)/100;//获取总的优惠券价格，发送优惠券使用事件通知

                    //店铺是否含有缓存自提点信息
                    if(shop.sid in this.userIssue) {
                        let _issue = this.userIssue[shop.sid];
                            shop.checkPlotId = _issue.issue_id || '';
                            shop.checkPlotName = _issue.issue_name || '';
                    }

                    //判断是否有不能购买的情况
                   let goodsList = shop.goods;
                   for(let g in goodsList){
                       let goods = goodsList[g];
                       let flag = goods.sent_status;
                       if(flag != '有货') {
                           _canBuy = false;
                           break;
                       }
                   }
                   //是否存在无货
                   if(_canBuy) {
                       this.canBuy = true;
                   } else {
                       this.canBuy = false;
                   }
                }

                //计算点击后的数据状态
                this.shopList = list;
                //新增余额支付的逻辑处理
                this.myMoneyPayHandler();
            },

            issueClick(shop){ //选择自提点
                console.log(shop);
                let options = {
                    classType: constant.Pop_Class_Type,
                    url: route.self_picker,
                    title: '选择小区',
                    params: {
                        sid: shop.sid
                    }
                };
                navigator.push(options);
            },

            /**支付跳转*/
            goToCash(){
                if(!this.canBuy) return false;

                if(!this.addressId){
                    modal.toast("您还没有收货地址");
                    return false;
                }

                let self = this;
                let goodsArr = {};
                let flag = true;
                for(let i=0; i<this.shopList.length; i++){
                    let shop = this.shopList[i];
                    if(shop.is_issue == 1) {/*含自提点的处理逻辑*/
                        if(!shop.checkPlotId) {
                            modal.toast(shop.sname + '店铺未设置自提点!');
                            flag = false;
                            return false;
                        } else {
                            goodsArr[shop.sid] = {
                                issue_id: shop.checkPlotId
                            }
                        }
                    } else {
                        goodsArr[shop.sid] = {
                            issue_id: ''
                        }
                    }

                    //优惠券
                    goodsArr[shop.sid].cs_no = shop.midcsno || '';

                    //商品数目
                    let _goods = shop.goods, tempArr = [];
                    for(let g in _goods){
                        tempArr.push(_goods[g].id + '_' + _goods[g].num);

                        //push该订单全部店铺商品
                        self.orderGoodsArr.push(_goods[g].id);
                    }
                    goodsArr[shop.sid].goods = tempArr.join('=');
                    goodsArr[shop.sid].sid = shop.sid;
                    goodsArr[shop.sid].beizhu = shop.beizhu || '';
                }
                if(!flag) return false;

                goodsArr = JSON.stringify(goodsArr);
                this.jumpCash(goodsArr);
            },

            /**调到收银台界面*/
            jumpCash(str) {
                let self = this;
                let _options = {
                    ordersinfo: str,
                    address: self.addressId,
                    defaultTotalPrice: self.actOrderTotalMoney.toFixed(2)
                };
                //来源
                if(self.from) _options.fromtype = self.from;
                //是否使用余额支付
                if(self.isMyMoney) _options.userMoney = self.costMyMoney;

                api.sendHttp('submitOrderCtrlApi', _options).then(res => {
                    //set storage购物车数据
                    let _cartData = res.data.cart || {};
                    if(Object.keys(_cartData).length){
                        cartService.storageCartInfo(_cartData);
                    }

                    //发送购物车生成订单通知
                    if(self.from == 'fromCart') { //来自购物车
                        //发送购物车生成订单通知 更新底部导航数据
                        notification.send(constant.EVENT_CART_TO_ORDER,_cartData);
                        //发送购物车生成订单通知 重置其他页面购物车数量通知
                        notification.send(constant.EVENT_CART_DELETE,self.orderGoodsArr);
                    }

                    //发送优惠券生成订单通知
                    if(self.orderTotalCoupon > 0) {
                        notification.send(constant.EVENT_COUPON_TO_ORDER,self.orderTotalCoupon);
                    }

                    let data = res.data || {};
                    let payId = data.payid || '';
                    let payMoney = data.pay_money || 0;
                    if(payMoney == '') payMoney = 0;

                    let hasOpennedNoSecur = data.open_nosecr, //是否成功开启免密支付签约
                        hasPaySuccessed = data.pay_success; //是否成功代扣

                    let signType = data.signtype;//签约类型
                    let signInfo = data.signinfo || [];//免密支付说明文案
                    let signImg = data.signimg;//签约二维码
                    let signTitle = data.signtitle; //签约标题
                    let signRemark = data.signremark; //签约mark


                    if(payMoney > 0) { //传递payId 对付款成功进行监听
                        if(hasOpennedNoSecur) {
                            /**已经开启免密支付代扣，直接扣款*/
                            if(hasPaySuccessed) {
                                /** 代扣成功，直接到支付成功界面 */
                                self.jumpToPaySuccPage(payId); //跳转到支付成功界面
                            } else {
                                /** 扣款失败则直接跳转付款收银台界面 */
                                navigator.pop();
                                let _options = {
                                    classType: constant.Drawer_Class_Type,
                                    url: route.cash,
                                    title: '收银台',
                                    params: {
                                        payId: payId
                                    }
                                };
                                navigator.push(_options);
                            }
                        } else {
                            /**未签约直接跳转到签约开通界面*/
                            navigator.pop();
                            let _options = {
                                classType: constant.Drawer_Class_Type,
                                url: route.new_cash,
                                title: '收银台',
                                params: {
                                    payMoney: payMoney,
                                    payId: payId,
                                    signType: signType,
                                    img: signImg,
                                    info: signInfo,
                                    title: signTitle,
                                    remark: signRemark
                                }
                            };
                            navigator.push(_options);
                        }
                    } else {
                        //不需要支付，直接跳转到支付成功界面
                        self.jumpToPaySuccPage(payId);
                    }
                }, res => {
                    modal.toast(res.msg);
                });
            },

            /**切换勾选余额支付*/
            switchMyMoneyPay() {
                this.isMyMoney = !this.isMyMoney;
                this.myMoneyPayHandler();
            },

            /**新增余额支付后的总金额处理函数*/
            myMoneyPayHandler() {
                 //新增余额支付，重新处理最终支付金额
                this.actOrderTotalMoney = this.totalMoney;

                if(this.isMyMoney) { //是否使用余额支付
                    //消耗的余额
                    this.costMyMoney = (this.actOrderTotalMoney - this.myMoneyResult) > 0 ? this.myMoneyResult : this.actOrderTotalMoney;
                    //计算最终支付总额
                    this.actOrderTotalMoney = (this.actOrderTotalMoney - this.myMoneyResult) > 0 ? this.actOrderTotalMoney - this.myMoneyResult : 0;
                }
            },
            /**付款成功跳转到支付成功页*/
            jumpToPaySuccPage(payId){
                navigator.pop();
                let options = {
                    classType: constant.PaySuccess_Class_Type,
                    title: '收银台',
                    params: {
                        payId: payId
                    }
                };
                navigator.push(options); //跳转到支付成功界面
            },
        },
        destroyed(){
            globalEvent.removeEventListener(constant.EVENT_ADDRESS_FROM_CONFIRM);
            globalEvent.removeEventListener(constant.EVENT_GET_SELFPICK);
        }
    }
</script>
